﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetJavap.JVM
{
    public class JavaObject
    {
        private static Dictionary<JavaClass, Dictionary<UInt16, Object>> _staticFieldCaches = new Dictionary<JavaClass, Dictionary<ushort, object>>();
        private static Dictionary<JavaClass, JavaObject> _staticInstanceCaches = new Dictionary<JavaClass, JavaObject>();

        private JavaClass _class;
        private Dictionary<UInt16,Object> _fieldValues;

        private Dictionary<UInt16, Object> _staticFieldCache;

        public JavaClass Class { get { return this._class; } }
        public Dictionary<UInt16, Object> FieldValues { get { return this._fieldValues; } }
        public Dictionary<UInt16, Object> StaticFields
        {
            get
            {
                if (this._staticFieldCache == null)
                {
                    this._staticFieldCache = GetStaticFieldCache(this._class);
                }
                return this._staticFieldCache;
            }
        }

        public static JavaObject GetStaticInstance(JavaClass cls)
        {
            JavaObject ins = null;
            if (!_staticInstanceCaches.TryGetValue(cls,out ins))
            {
                ins = new JavaObject(cls);
                _staticInstanceCaches[cls] = ins;
            }
            return ins;
        }

        public static Dictionary<UInt16, Object> GetStaticFieldCache(JavaClass cls)
        {
            Dictionary<UInt16, Object> staticFieldCache = null;
            if (!_staticFieldCaches.TryGetValue(cls, out staticFieldCache))
            {
                staticFieldCache = new Dictionary<ushort, object>();
                _staticFieldCaches[cls] = staticFieldCache;
            }
            return staticFieldCache;
        }
        public static Dictionary<JavaClass, Dictionary<UInt16, Object>> StaticFieldCaches { get { return _staticFieldCaches; } }

        public JavaObject(JavaClass cls)
        {
            this._class = cls;
            this._fieldValues = new Dictionary<ushort, object>();
        }
    }
}
